package com.yjyw.tiexie.application;

import android.app.Activity;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationChannelGroup;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;

import androidx.multidex.MultiDex;

import com.alibaba.android.arouter.launcher.ARouter;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.yjyw.tiexie.BuildConfig;
import com.yjyw.tiexie.R;
import com.yjyw.tiexie.activity.login.StartPageActivity;
import com.yjyw.tiexie.common.AppFrontBackHelper;
import com.yjyw.tiexie.common.Constant;
import com.yjyw.tiexie.common.OnBack;
import com.yjyw.tiexie.common.OnFront;
import com.yjyw.tiexie.db.DaoManager;
import com.yjyw.tiexie.util.FileUtils;
import com.yjyw.tiexie.util.LogUtil;
import com.yjyw.tiexie.util.StorageUtil;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

public class MyApplication extends Application {

    private static Context mContext;

    public static Context getContext() {
        return mContext;
    }

    private static final String TAG = "Init";

    private static MyApplication instance;

    // login user name
    public final String PREF_USERNAME = "username";

    /**
     * nickname for current user, the nickname instead of ID be shown when user receive notification from APNs
     */
    public static String currentUserNick = "";

//    private String ugcKey = "365d93abded839c5cbc6f658eaa1f593";
//    private String ugcLicenceUrl = "https://license.vod2.myqcloud.com/license/v2/1306435952_1/v_cube.license";

//    private Paint mPaint;

    @Override
    public void onCreate() {
        MultiDex.install(this);
        super.onCreate();
        mContext = this;
        instance = this;
        //设置是否显示log打印
        LogUtil.setIsDebug(true);
        if (BuildConfig.DEBUG) {           // These two lines must be written before init, otherwise these configurations will be invalid in the init process
            ARouter.openLog();     // Print log
            ARouter.openDebug();   // Turn on debugging mode (If you are running in InstantRun mode, you must turn on debug mode! Online version needs to be closed, otherwise there is a security risk)
        }
        // Anr检测
//        BlockCanary.install(this, new AppBlockCanaryContext()).start();
        ARouter.init(MyApplication.this); // As early as possible, it is recommended to initialize in the Application
        initChannel();
        //初始化路径
        initDir();
        //初始化GreenDAO
        DaoManager.getInstance().init(this);

        SharedPreferences sp = getSharedPreferences("isPlace", 0);
        String place = sp.getString("agree", "");
        if ("" == place) {
            LogUtil.e("place", "未同意");
            //第一次用户还没有同意用户隐私政策 不初始化sdk
        } else {
            LogUtil.e("place", "同意初始化app");
            initConfig();
            UMConfigure.setLogEnabled(false);
            UMConfigure.setEncryptEnabled(true);
            UMConfigure.init(this, "619b5f87e0f9bb492b687318", "tx", UMConfigure.DEVICE_TYPE_PHONE, "");
            // 初始化 友盟统计 SDK
            MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
            /** 设置是否对日志信息进行加密, 默认false(不加密). */
            MobclickAgent.enableEncrypt(true);//6.0.0版本及以后
            MobclickAgent.setDebugMode(false);
            //初始化 友盟分享 SDK
            UMShareAPI.get(this);
            // 自动采集选择
//            MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
            initX5();
        }

        registerActivityLifecycleCallbacks(new StatisticActivityLifecycleCallback());
    }


    class StatisticActivityLifecycleCallback implements ActivityLifecycleCallbacks {
        private int foregroundActivities = 0;
        private boolean isChangingConfiguration;

        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {
            // 当Activity创建，我们拿到DecorView，使用Paint进行重绘
//            View decorView = activity.getWindow().getDecorView();
//            decorView.setLayerType(View.LAYER_TYPE_HARDWARE, mPaint);

            LogUtil.i(TAG, "onActivityCreated bundle: " + bundle);
            if (bundle != null) { // 若bundle不为空则程序异常结束
                // 重启整个程序
                Intent intent = new Intent(activity, StartPageActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }

        @Override
        public void onActivityStarted(Activity activity) {
            foregroundActivities++;
            if (foregroundActivities == 1 && !isChangingConfiguration) {
                // 应用切到前台
                LogUtil.i(TAG, "application enter foreground");
            }
            isChangingConfiguration = false;
        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {
            foregroundActivities--;
            if (foregroundActivities == 0) {
                // 应用切到后台
                LogUtil.i(TAG, "application enter background");
            }
            isChangingConfiguration = activity.isChangingConfigurations();
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {

        }
    }

    private void initAppHelper() {
        AppFrontBackHelper helper = new AppFrontBackHelper();
        helper.register(this, new AppFrontBackHelper.OnAppStatusListener() {
            @Override
            public void onFront() {
                OnFront.getInstance().onFront();
            }

            @Override
            public void onBack() {
                OnBack.getInstance().onBack();
            }
        });
    }

    private void initX5() {
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。

        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                LogUtil.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
//        android11 oppo手机崩溃 暂时去掉
//        x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }


    /**
     * 各个平台的配置，建议放在全局Application或者程序入口
     */
    public void initConfig() {
    }

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(android.R.color.transparent, R.color.colorPrimary);//全局设置主题颜色
                MaterialHeader header = new MaterialHeader(context);
                header.setColorSchemeResources(R.color.main, R.color.main, R.color.main, R.color.main);
                return header;//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }


    private void initChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (nm != null) {
                NotificationChannelGroup notificationChannelGroup = new NotificationChannelGroup("1", "自定义通知组");
                nm.createNotificationChannelGroup(notificationChannelGroup);
                NotificationChannel notificationChannel = new NotificationChannel("1", "自定义通知", NotificationManager.IMPORTANCE_HIGH);
                notificationChannel.setGroup("1");
                notificationChannel.enableLights(true);
                notificationChannel.enableVibration(true);
//                notificationChannel.setSound("android.resource://包名/raw/铃声文件", null);    //设置自定义铃声
                nm.createNotificationChannel(notificationChannel);
            }
        }
    }


    private void initDir() {

        if (StorageUtil.externalMemoryAvailable()) {
            Constant.ROOT_PATH = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/" + BuildConfig.MX_USER_TYPE + "/";

            Constant.TEMP_PIC_PATH = Constant.ROOT_PATH + "temp_pic/";
            Constant.TEMP_FILE_PATH = Constant.ROOT_PATH + "temp_file/";

        } else {
            Constant.ROOT_PATH = getApplicationContext().getFilesDir()
                    .getAbsolutePath() + "/";

            Constant.TEMP_PIC_PATH = Constant.ROOT_PATH + "temp_pic/";
            Constant.TEMP_FILE_PATH = Constant.ROOT_PATH + "temp_file/";

        }
        FileUtils.createPath(Constant.ROOT_PATH);
        FileUtils.createPath(Constant.TEMP_PIC_PATH);
        FileUtils.createPath(Constant.TEMP_FILE_PATH);

    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        ARouter.getInstance().destroy();
    }
}

